from urllib.parse import urlencode

from django.http import JsonResponse
from django.shortcuts import redirect

from AiJiaHome.utils.response_code import RET

from django.contrib.auth.decorators import wraps


def get_html_file(request, file_name):
    # 判断是否是网站的Logo,如果不是,添加前缀
    if file_name != "favicon.ico":
        file_name = "static/html/" + file_name

    params = request.GET
    if params:
        result = urlencode(params)
        return redirect(file_name + '?{}'.format(result))
    return redirect(file_name)

def index(request):
    return redirect('/static/html/index.html')


def login_required_json(view_func):
    '''
    判断用户是否登录的装饰器,病返回json
    :param view_func:
    :return:
    '''

    @wraps(view_func)
    def wrapper(request, *args, **kwargs):

        # 用户未登录,返回json
        if not request.user.is_authenticated():
            return JsonResponse({'errno': RET.SESSIONERR, 'errmsg': '用户未登录'})
        else:
            return view_func(request, *args, **kwargs)

    return wrapper


class LoginRequiredJSONMixin(object):
    '''判断用户是否登录,并返回json的Mixin类'''


    @classmethod
    def as_view(cls, **initkwargs):
        view = super().as_view(**initkwargs)
        return login_required_json(view)